#include "TcpServer.hpp"
#include "Protocol.hpp"
#include"Daemon.hpp"
using namespace na_Tcpserver;
using namespace na_protocol;
// ./CalServer server_port
static void Usage(char *proc)
{
    std::cout << "\nUsage" << proc << " serve_port" << std::endl;
}
Response calculatorHelp(Request req)
{
    Response res(0, 0);
    switch (req._op)
    {
    case '+':
        res._result = req._x + req._y;
        break;
    case '-':
        res._result = req._x - req._y;
        break;
    case '*':
        res._result = req._x * req._y;
        break;
    case '/':
        if (req._y == 0)
            res._code = 1;
        else
            res._result = req._x / req._y;
        break;
    case '%':
        if (req._y == 0)
            res._code = 2;
        else
            res._result = req._x % req._y;
        break;
    default:
        res._code = 3;
        break;
    }
    return res;
}
void calculator(int sock)
{

    while (true)
    {

        std::string buff;
        bool ret = Recv(sock, &buff); // 从客户端读信息
        
        if (!ret)
        {

            break;
        }
        //std::cout<<"读取成功"<<std::endl;
       // std::cout<<buff<<std::endl;
        std::string str = Decode(buff); // 从读到的信息中提取有效信息
        if (str.empty())                // 读取到的报文无法提取出一条完整的有效信息，继续读取
        {
            continue;
        }
        //logMessage(NORMAL,"%s%s%s","server receive a task:",str.c_str());
        std::cout<<"server receive a task:"<<str<<std::endl;
        Request req;
        req.Deserialized(str); // 提取到的有效信息进行反序列化
        Response res=calculatorHelp(req);//计算结果
        std::string package=res.Serialize();//结果进行序列化
        package=Encode(package);//序列化的结果添加报头以及SEP分隔符
        Send(sock,package);//完整的报文信息发送给客户端


    }
    close(sock);
}
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
    }
    uint16_t service_port = atoi(argv[1]);
    //myDaemon();//服务器成为守护进程，永久不退出
    TcpServer *tcp_server = new TcpServer(service_port);
    tcp_server->BindServer(calculator);
    tcp_server->start();

    return 0;
}